/*
 * ScoreRequest.java is part of htn-example.
 *
 * ScoreRequest.java is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ScoreRequest.java is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ScoreRequest.java.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.htn.telescopes.rtml;

import java.text.ParseException;

import javax.xml.parsers.ParserConfigurationException;

import org.htn.rtml.RTMLRequest;
import org.htn.telescopes.rtml.parser.*;

public class ScoreRequest implements RTMLRequest
{
	public String send(Object rtml)
	{
		if (rtml instanceof String)
			return doScore(null, (String)rtml);
		else
			return null;
	}
	
	public String send(String id, Object rtml)
	{
		if (rtml instanceof String)
			return doScore(id, (String)rtml);
		else
			return null;
	}
	
	private String doScore(String id, String rtml)
	{
		// id not used for scoring... ignore
		
		// parse the request
		RTMLDocument request = null;
		try
		{
			request = parse(rtml);
		}
		catch (ParserConfigurationException pcex)
		{
			
		} 
		catch (RTMLException e) 
		{
			
		} 
		catch (ParseException e) 
		{
			
		}
		
		// perform scoring
		RTMLDocument result = null;
		ScoreDocumentHandler handler = new ScoreDocumentHandler();
		try 
		{
			result = handler.handleScore(request);
		} 
		catch (Exception e) 
		{
			// TODO 
		}
		
		// Reformat rtml object model into a string.
		RTMLCreate refact = null;
		String resultString = null;
		try 
		{
			refact = new RTMLCreate();
			refact.setDoctypeSystemID(RTMLDocument.RTML_VERSION_31);
			refact.create(result);
			resultString = refact.toXMLString();
		} 
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultString;
	}
	
	private RTMLDocument parse(String rtml) throws ParserConfigurationException, RTMLException, ParseException
	{
	    RTMLParser parser = new RTMLParser();
	    parser.init(true);
	    return parser.parse(rtml);
	}
}
